package com.base.pub.persistence;

import java.io.Serializable;
import java.util.Properties;

import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.plugin.Interceptor;
import org.hibernate.dialect.DB2Dialect;
import org.hibernate.dialect.DerbyDialect;
import org.hibernate.dialect.Dialect;
import org.hibernate.dialect.H2Dialect;
import org.hibernate.dialect.HSQLDialect;
import org.hibernate.dialect.MySQLDialect;
import org.hibernate.dialect.OracleDialect;
import org.hibernate.dialect.PostgreSQLDialect;
import org.hibernate.dialect.SQLServer2005Dialect;
import org.hibernate.dialect.SybaseDialect;

import com.base.pub.config.GlobalConfig;
import com.base.pub.util.Reflections;

/**
 * 分页拦截器基类
 * 
 */
public abstract class MybatisBaseInterceptor implements Interceptor, Serializable {

	private static final long		serialVersionUID	= 1L;

	protected static final String	PAGE				= "page";

	protected static final String	DELEGATE			= "delegate";

	protected static final String	MAPPED_STATEMENT	= "mappedStatement";

	protected Log					log					= LogFactory.getLog(this.getClass());

	protected Dialect				DIALECT;

	/**
	 * 对参数进行转换和检查
	 */
	@SuppressWarnings("unchecked")
	protected static MybatisPageFrag<Object> convertParameter(Object parameterObject, MybatisPageFrag<Object> page) {
		try {
			if (parameterObject instanceof MybatisPageFrag) {
				return (MybatisPageFrag<Object>) parameterObject;
			} else {
				return (MybatisPageFrag<Object>) Reflections.getFieldValue(parameterObject, PAGE);
			}
		} catch (Exception e) {
			return null;
		}
	}

	protected void initProperties(Properties p) {
		Dialect dialect = null;
		String dbType = GlobalConfig.getConfig("jdbc.type");
		if ("db2".equals(dbType)) {
			dialect = new DB2Dialect();
		} else if ("derby".equals(dbType)) {
			dialect = new DerbyDialect();
		} else if ("h2".equals(dbType)) {
			dialect = new H2Dialect();
		} else if ("hsql".equals(dbType)) {
			dialect = new HSQLDialect();
		} else if ("mysql".equals(dbType)) {
			dialect = new MySQLDialect();
		} else if ("oracle".equals(dbType)) {
			dialect = new OracleDialect();
		} else if ("postgre".equals(dbType)) {
			dialect = new PostgreSQLDialect();
		} else if ("mssql".equals(dbType) || "sqlserver".equals(dbType)) {
			dialect = new SQLServer2005Dialect();
		} else if ("sybase".equals(dbType)) {
			dialect = new SybaseDialect();
		}
		if (dialect == null) {
			throw new RuntimeException("mybatis dialect error.");
		}
		DIALECT = dialect;
	}
}
